package keyword_volatile;

import java.util.concurrent.TimeUnit;

/**
 * User: ZhangJuntao
 * Date: 14-2-13
 * Time: 下午10:07
 */
public class VolatileTest {
  static class Test1 implements Runnable {
    private volatile boolean pleaseStop = false;

    public void tellMeToStop() {
      pleaseStop = true;
    }

    public void run() {
      long i = 0L;
      while (!pleaseStop) {
        i++;
      }
      System.out.println(i);
    }

    public static void main(String[] args) throws InterruptedException {
      Test1 test1 = new Test1();
      new Thread(test1).start();
      TimeUnit.MILLISECONDS.sleep(1000);
      test1.tellMeToStop();
      System.out.println("end");
    }
  }

  static class Test2 implements Runnable {
    private boolean pleaseStop = false;

    public void run() {
      int i = 0;
      while (!pleaseStop) {
        i++;
        //非volatile变量并不是 不能获取对象更新值，只是没有volatile变量来的那么及时
        //cpu在yield之后 其他线程获取优先执行的机会之后，先把工作内存的值写入主内存，
        // 回来继续执行时，将会从主内存中重新获取最新值
        Thread.yield();
      }
      System.out.println(i);
    }

    public void tellMeToStop() {
      pleaseStop = true;
    }

    public static void main(String[] args) throws InterruptedException {
      Test2 test2 = new Test2();
      new Thread(test2).start();
      TimeUnit.MILLISECONDS.sleep(1000);
      test2.tellMeToStop();
      System.out.println("end");
    }
  }

  /**
   * 会一直执行，直到让出CPU
   */
  static class Test3 implements Runnable {
    private boolean pleaseStop = false;

    public void run() {
      int i = 0;
      while (!pleaseStop) {
        i++;
      }
      System.out.println(i);
    }

    public void tellMeToStop() {
      pleaseStop = true;
    }

    public static void main(String[] args) throws InterruptedException {
      Test3 test = new Test3();
      new Thread(test).start();
      TimeUnit.MILLISECONDS.sleep(1000);
      test.tellMeToStop();
      System.out.println("end");
    }
  }
}

